package com.example.ccj.u.power;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.ccj.b.c.dialog.DrawingBoardDialog;
import com.example.ccj.u.ActivityUtils;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.PermissonUtils;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.ToastUtils;
import com.example.ccj.u.array.ArrayUtils;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 申请权限
 */
public class PowerPer {

    /**
     * 获取所有文件的访问权限
     * @param activity 上下文
     * @return
     */
    public static boolean getAllFilePower(Activity activity){
        //获取所有文件的管理权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 先判断有没有权限
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + activity.getPackageName()));
                activity.startActivityForResult(intent, 100);
                return false;
            } else {
                return true;
            }
        }
        return true;
    }


    /**
     * 获取图片选择权限
     * @param context 上下文
     */
    public static boolean getCameraPower(Context context){
        String[] imagePower = new String[]{Manifest.permission.CAMERA,  //相机
//                Manifest.permission.READ_EXTERNAL_STORAGE,               //外部存储
//                Manifest.permission.READ_EXTERNAL_STORAGE,      //外部存储
//                Manifest.permission.WRITE_EXTERNAL_STORAGE,     //写存储
        };
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
            imagePower = new String[]{Manifest.permission.CAMERA,   //相机
                    Manifest.permission.READ_MEDIA_AUDIO,           //音频
//                    Manifest.permission.READ_EXTERNAL_STORAGE,      //外部存储
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,     //写存储
                    Manifest.permission.READ_MEDIA_IMAGES,          //相册
                    Manifest.permission.READ_MEDIA_VIDEO};          //视频
        }
        return checkPower(context,imagePower);
    }

    /**
     * 获取粗略位置定位权限
     * @param context 上下文
     */
    public static boolean getLocationCoarsePower(Context context){
        String[] locationCoarsePower = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,  //粗略位置
//                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,  //读取缓存数据
//                android.Manifest.permission.READ_EXTERNAL_STORAGE,   //外部存储
//                android.Manifest.permission.READ_PHONE_STATE,       //读取手机当前的状态
        };
        return checkPower(context,locationCoarsePower);
    }

    /**
     * 获取精确位置定位权限
     * @param context 上下文
     */
    public static boolean getLocationFinePower(Context context){
        String[] locationPower = new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION, //模糊定位
                android.Manifest.permission.ACCESS_FINE_LOCATION,   //精确定位
//                android.Manifest.permission.WRITE_EXTERNAL_STORAGE, //读取缓存数据
//                android.Manifest.permission.READ_EXTERNAL_STORAGE,  //外部存储
//                android.Manifest.permission.READ_PHONE_STATE,       //读取手机当前的状态
        };
        return checkPower(context,locationPower);
    }

    /**
     * 获取扫码权限
     * @param context 上下文
     */
    public static boolean getScanCodePower(Context context){
        String[] scanCodePower = new String[]{Manifest.permission.CAMERA,  //相机
//                Manifest.permission.READ_EXTERNAL_STORAGE,      //外部存储
//                Manifest.permission.WRITE_EXTERNAL_STORAGE,     //读取缓存数据
        };
        return checkPower(context,scanCodePower);
    }

    /**
     * 检查是否具备权限
     * @param context 上下文
     * @param locationPower 权限列表
     * @return true 具备  false 不具备
     */
    public static boolean checkPower(Context context, String[] locationPower){
        boolean isHavePower = true;
        String[] locationPower1 = new String[locationPower.length];
        //获取权限
        int i = 0;
        for (String s : locationPower) {
            if (ContextCompat.checkSelfPermission(context, s) != PackageManager.PERMISSION_GRANTED) {
                isHavePower = false;
                locationPower1[i++] = s;
                LogUtils.e("未赋予的权限：" + s);
            }
        }

        if (!isHavePower && i > 0) {
            String[] strings = ArrayUtils.subArray(locationPower1, 0, i - 1);
            PowerPer.getMultiPermission(context,999,strings);
        }
        return isHavePower;
    }

    /**
     * 获取单个权限
     * @param context
     * @param requestCode
     * @param permission
     */
    public static void getOnePermission(Context context, int requestCode,String permission){
        // checkSelfPermission() 检测权限
        if (ContextCompat.checkSelfPermission(context, permission)
                != PackageManager.PERMISSION_GRANTED) {
            //TODO 申请存储权限
            ActivityCompat.requestPermissions(ActivityUtils.getTopActivity(), new String[]{permission},
                    requestCode);
        }
    }

    public static void getMultiPermission(Context context, int requestCode,String... permission){
        List<String> getPermission = new ArrayList<>();
        // checkSelfPermission() 检测权限
        for (String s : permission) {
            if (ContextCompat.checkSelfPermission(context, s) != PackageManager.PERMISSION_GRANTED) {
                getPermission.add(s);
            }
        }
        String[] hhh = new String[getPermission.size()];
        for (int i = 0; i < getPermission.size(); i++) {
            hhh[i] = getPermission.get(i);
        }
        if (hhh.length < 1) return;
        ActivityCompat.requestPermissions(ActivityUtils.getTopActivity(),hhh,
                requestCode);
    }


    /*
     * 获取申请多个权限的结果
     * */
    public static void requestMultiResult(Activity activity ,int requestCode,@NonNull String[] permissions, @NonNull int[] grantResults,
                                          PermissionListener permissionListener){
        if (activity == null) {
            return;
        }
        Map<String,Integer> perms = new HashMap<>();
        ArrayList<String> notGranted = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            perms.put(permissions[i],grantResults[i]);
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                notGranted.add(permissions[i]);
            }
        }
        if (notGranted.isEmpty()) {
            Toast.makeText(activity,"all permission succewss",Toast.LENGTH_SHORT).show();
            permissionListener.onPermissionGranted(requestCode);
        }else {
            openSettingActivity(activity,"those permission need granted!");
        }
    }


    /*打开设置界面*/
    private static void openSettingActivity(final Activity activity, String msg) {
        showMessageOKCancel(activity, msg, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
                intent.setData(uri);
                activity.startActivity(intent);
            }
        });
    }


    /* 弹出是否打开的对话框*/
    private static void showMessageOKCancel(Activity activity, String msg, DialogInterface.OnClickListener oklistener){
        new AlertDialog.Builder(activity)
                .setMessage(msg)
                .setPositiveButton("OK",oklistener)
                .setNegativeButton("Cancel",null)
                .create().show();
    }


}
